package com.concurrent.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: zhouyang
 * @descrpition: Condition测试 实现通知/唤醒模式
 * @time: 2019-05-09 19:48
 */
@Slf4j
public class ConditionTest {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    //单纯的唤醒线程并不能导致其它线程获取锁 持有该锁的线程不仅要唤醒其它AQS中的线程 还要手动放弃锁
    public static void main(String[] args) {
        new Thread(() -> {
            lock.lock();
            log.info("wait signal");
            try {
                condition.await();//使线程进入等待队列 并释放锁 线程状态变为等待状态
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            lock.lock();
            log.info("get lock");
            try {
                Thread.sleep(5000);
                condition.signalAll();
                log.info("release signal");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }).start();
    }

}
